/**
 * Created by moc on 2016/3/29.
 */
var express = require('express');
var router = express.Router();
var User = require('../model/model.js').User
var Note = require('../model/model.js').Note
var crypto = require('crypto');
var aes = require('./aes.js')

var service = require('./service.js')

var pwEncode = function (pw) {
    console.log(pw)
    var sha1 = crypto.createHash('sha1');
    sha1.update(pw)
    return sha1.digest('hex')
}

router.post('/login',
    function (req, res, next) {
        User.findOne({username: req.body.username}, function (err, doc) {
            var name = req.body.username
            var pw = req.body.password

            if (doc) {
                if (pwEncode(pw) == doc.password) {
                    res.cookie('user', aes.encode(doc), {maxAge: 1000 * 3600 * 24 * 7})
                    console.log(res.cookie)
                    res.json({code: 0})
                } else {
                    res.json({code: 1, msg: "wrong password"})
                }
            } else {
                res.json({code: 1, msg: "name not exist"})
            }
        })
    }
)

router.post('/register',
    function (req, res, next) {
        User.findOne({username: req.body.username}, function (err, doc) {
            var name = req.body.username
            var pw = req.body.password
            name = name.trim()
            pw = pw.trim()
            var reName = /\w{3,20}/
            var repw = /\w{6,20}/
            if (!reName.test(name)) {
                res.json({code: 1, msg: "含有非法字符"})
            } else if (!repw.test(pw)) {
                res.json({code: 1, msg: "含有非法字符"})
            }
            console.log(err)
            if (doc) {
                res.json({code: 1, msg: "name exists"})
            } else {
                var pwsha = pwEncode(pw)
                console.log(name)
                User.save({
                    username: name,
                    password: pwsha,
                },function (err, doc) {
                    res.json({code: 0})
                })

            }
        })
    }
)

router.post('/logout',
    function (req, res, next) {
        res.cookie('user', 0)
        res.json({code: 0})
    }
)

router.post('/newnote',
    function (req, res, next) {
        var user = service.checkLogin(req, res)
        var title = req.body.title
        var content = req.body.content
        var username = user.username
        Note.save({
            title: title,
            content: content,
            username: username
        },function (err, doc) {
            res.json({code: 0})
        })

    }
)

module.exports = router


